<?php
/**
 * MySql
 * The Samble mysql base class.
 *
 * @author Lim Afriyadi
 * @version pre-alpha
 * @package Samble
 * @subpackage db
 * @license GNU/GPL
 */
 class SDbMySql extends SDbTransaction implements SDbCrud
 {
     /**
      * Check current Mysql connection state.
      * 
      * @return boolean
      */
     public function isConnected()
     {
         return $this->b_State;
     }
     /**
      * Mysql query execution for 'SELECT' statement.
      *
      * @param string $s_Query
      * @return boolean
      */
     public function select( $s_Query="" )
     {
         if( $this->isOnQuery() )
         {
             $this->clearResultSet();
         }
         $this->clearResultSet();
         if( !$this->b_Query && $this->b_State )
         {
             $this->o_Query = mysql_query( $s_Query );
             if( $this->o_Query !== false )
             {
                $this->s_Stmt = $s_Query;
                $this->b_Query = true;
                return true;
             }
         }
         return false;
     }
     /**
      * Mysql query execution for 'DELETE' statement.
      *
      * @param string $s_Query
      * @return boolean
      */
     public function delete( $s_Query="" )
     {
         if( !$this->b_Query && $this->b_State )
         {
             $this->o_Query = mysql_query( $s_Query );
             if( $this->o_Query !== false )
             {
                $this->s_Stmt = $s_Query;
                $this->b_Query = true;
                return true;
             }
         }
         return false;
     }
     /**
      * Mysql query execution for 'INSERT' statement.
      *
      * @param string $s_Query
      * @return boolean
      */
     public function insert( $s_Query="" )
     {
         if( !$this->b_Query && $this->b_State )
         {
             $this->o_Query = mysql_query( $s_Query );
             if( $this->o_Query !== false )
             {
                $this->s_Stmt = $s_Query;
                $this->b_Query = true;
                return true;
             }
         }
         return false;
     }
     /**
      * Mysql query execution for 'UPDATE' statement.
      *
      * @param string $s_Query
      * @return boolean
      */
     public function update( $s_Query="" )
     {
         if( !$this->b_Query && $this->b_State )
         {
             $this->o_Query = mysql_query( $s_Query );
             if( $this->o_Query !== false )
             {
                $this->s_Stmt = $s_Query;
                $this->b_Query = true;
                return true;
             }
         }
         return false;
     }
     /**
      * Check the class status whether there was an unexected
      * statement query.
      *
      * @return boolean
      */
     public function isOnQuery()
     {
         return $this->b_Query;
     }
     
     /**
      * Mysql persistent connection function, all parameters are mandatory.
      * This function will return true if mysql persistent connection connect successfully
      * to mysql server and errors message of the connection failures.
      *
      * @param string $s_Host
      * @param int $i_Port
      * @param string $s_Uname
      * @param string $s_Pwd
      * @param string $s_Db
      * @param boolean $b_Persistent
      * @return boolean
      */
     public function pconnect( $s_Host="",$i_Port="",$s_Uname="",$s_Pwd="",$s_Db="",$b_Persistent=false )
     {
         $s_Err_Msg = "MySQL connection failed due to the followings :<br/>";
         // Check host parameter.
         if( $s_Host )
         {
            $this->s_Host = $s_Host;
            // Check port parameter.
            if( !is_numeric( $i_Port ) )
            {
                $this->i_Port = 3306;
            }
            else
            {
                $this->i_Port = $i_Port;
            }
            // Check username parameter.
            if( $s_Uname )
            {
                $this->s_Uname = $s_Uname;
                // Check password parameter.
                if( $s_Pwd )
                {
                    $this->s_Pwd = $s_Pwd;
                    // Check database parameter.
                    if( $s_Db )
                    {
                        $this->s_Db = $s_Db;
                        // Connection status
                        if( @mysql_pconnect( $this->s_Host, $this->s_Uname, $this->s_Pwd ) )
                        {
                            // Database status
                            if( @mysql_select_db( $this->s_Db ) )
                            {
                                $this->b_State = true;
                                return true;
                            }
                            $s_Err_Msg .= ' - Database does not exists<br/>';
                        }
                        else
                        {
                            $s_Err_Msg .= ' - Connection to MySQL server failed<br/>';
                        }
                    }
                    else
                    {
                        $s_Err_Msg .= ' - the $s_Db parameter is not defined<br/>';
                    }
                }
                else
                {
                    $s_Err_Msg .= ' - the $s_Pwd paramenter is not defined<br/>';
                }
            }
            else
            {
                $s_Err_Msg .= ' - the $s_Uname parameter is not defined<br/>';
            }
          }
          else
          {
              $s_Err_Msg .= ' - the $s_Host parameter not defined<br/>';
          }
          Samble::getObject( "ErrorHandler" )->error( $s_Err_Msg.'Please check your php file.' );
          $this->b_State = false;
          return false;
     }
     /**
      * Disconnect from an established mysql connection session.
      *
      * @return boolean
      */
     public function disconnect()
     {
         if( $this->isConnected() )
         {
            $state = mysql_close();
            $this->b_State = false;
            return true;
         }
         return false;
     }
     /**
      * Retrun result set of last mysql query statement
      * return false if there was no generated row by last query execution.
      *
      * @return array || false
      */
     public function getResultSet()
     {
         if( $this->isOnQuery() )
         {
             $i = 0;
             while( $result = mysql_fetch_array( $this->o_Query ) )
             {
                 $this->a_Result_Set[$i] = $result;
                 $i++;
             }
             return $this->a_Result_Set;
         }
         return false;
     }
     /**
      * Count number of rows generated by last mysql query statement.
      * return false if there was no generated row by last query execution.
      * 
      * @return int || false
      */
     public function numRows()
     {
         if( $this->isOnQuery() )
         {
             return mysql_num_rows( $this->o_Query );
         }
         return false;
     }
     /**
      * Initialize Mysql connection via unix socket.
      * 
      * @param string $sPath
      * @param string $s_Uname
      * @param string $s_Pwd
      * @param string $s_Db
      * @return boolean
      */
     public function sock( $sPath="",$s_Uname="",$s_Pwd="",$s_Db="" )
     {
         $s_Err_Msg = "MySQL connection failed due to the followings :<br/>";
         // Check socket path parameter.
         if( $sPath )
         {
            $this->sSocketPath = $sPath;
            // Check username parameter.
            if( $s_Uname )
            {
                $this->s_Uname = $s_Uname;
                // Check password parameter.
                if( $s_Pwd )
                {
                    $this->s_Pwd = $s_Pwd;
                    // Check database parameter.
                    if( $s_Db )
                    {
                        $this->s_Db = $s_Db;
                        // Connection status
                        if( @mysql_connect( $this->s_Host, $this->s_Uname, $this->s_Pwd ) )
                        {
                            // Database status
                            if( @mysql_select_db( $this->s_Db ) )
                            {
                                $this->b_State = true;
                                return true;
                            }
                            $s_Err_Msg .= ' - Database does not exists<br/>';
                        }
                        else
                        {
                            $s_Err_Msg .= ' - Connection to MySQL server failed<br/>';
                        }
                    }
                    else
                    {
                        $s_Err_Msg .= ' - the $s_Db parameter is not defined<br/>';
                    }
                }
                else
                {
                    $s_Err_Msg .= ' - the $s_Pwd paramenter is not defined<br/>';
                }
            }
            else
            {
                $s_Err_Msg .= ' - the $s_Uname parameter is not defined<br/>';
            }
          }
          else
          {
              $s_Err_Msg .= ' - the $sPath parameter is not defined<br/>';
          }
          Samble::getObject( "ErrorHandler" )->error( $s_Err_Msg.'Please check your php file.' );
          $this->b_State = false;
          return false;
     }
     /**
      * Clear cached Mysql query result set.
      */
     public function clearResultSet()
     {
         $this->a_Result_Set = array();
         $this->b_Query = false;
     }
     /**
      * Initialize Mysql persistent connection via unix socket.
      * 
      * @param string $sPath
      * @param string $s_Uname
      * @param string $s_Pwd
      * @param string $s_Db
      * @param boolean $b_Persistent
      */
     public function psock( $sPath="",$s_Uname="",$s_Pwd="",$s_Db="",$b_Persistent=false )
     {
         echo "J";
     }
     /**
      * Clear cached MySQL query statement.
      */
     public function clearQuery()
     {
         $this->s_Stmt = "";
     }

     /**
      * Mysql basic connection function, all parameters are mandatory.
      * This function will return true if mysql connect successfully
      * and errors message of the connection failures.
      *
      * @param string $s_Host
      * @param int $i_Port
      * @param string $s_Uname
      * @param string $s_Pwd
      * @param string $s_Db
      * @return boolean
      */
     public function connect( $s_Host="",$i_Port=3306,$s_Uname="",$s_Pwd="",$s_Db="" )
     {
         $s_Err_Msg = "MySQL connection failed due to the followings :<br/>";
         // Check host parameter.
         if( $s_Host )
         {
            $this->s_Host = $s_Host;
            // Check port parameter.
            if( !is_numeric( $i_Port ) )
            {
                $this->i_Port = 3306;
            }
            else
            {
                $this->i_Port = $i_Port;
            }
            // Check username parameter.
            if( $s_Uname )
            {
                $this->s_Uname = $s_Uname;
                // Check password parameter.
                if( $s_Pwd )
                {
                    $this->s_Pwd = $s_Pwd;
                    // Check database parameter.
                    if( $s_Db )
                    {
                        $this->s_Db = $s_Db;
                        // Connection status
                        if( @mysql_connect( $this->s_Host, $this->s_Uname, $this->s_Pwd ) )
                        {
                            // Database status
                            if( @mysql_select_db( $this->s_Db ) )
                            {
                                $this->b_State = true;
                                return true;
                            }
                            $s_Err_Msg .= ' - Database does not exists<br/>';
                        }
                        else
                        {
                            $s_Err_Msg .= ' - Connection to MySQL server failed<br/>';
                        }
                    }
                    else
                    {
                        $s_Err_Msg .= ' - the $s_Db parameter is not defined<br/>';
                    }
                }
                else
                {
                    $s_Err_Msg .= ' - the $s_Pwd paramenter is not defined<br/>';
                }
            }
            else
            {
                $s_Err_Msg .= ' - the $s_Uname parameter is not defined<br/>';
            }
          }
          else
          {
              $s_Err_Msg .= ' - the $s_Host parameter not defined<br/>';
          }
          Samble::getObject( "ErrorHandler" )->error( $s_Err_Msg.'Please check your php file.' );
          $this->b_State = false;
          return false;
     }

    public function dbDelete($s_Table, $a_Conditions)
    {
        $this->clearResultSet();
        if(!is_array($a_Conditions) || $s_Table == null)
        {
            Samble::getObject( "ErrorHandler" )->error('Incorrect parameters given at file: ' . __FILE__ . ' on line :' . __LINE__);
            return false;
        }
        $s_Stmt = "DELETE FROM " . $s_Table . " WHERE ";
        foreach($a_Conditions as $s_Key => $s_Value)
        {
            $s_Stmt .= " $s_Key = '$s_Value' AND ";
        }
        $s_Stmt = rtrim($s_Stmt, ' AND');
        $this->o_Query = mysql_query($s_Stmt);
        if($this->o_Query)
        {
            $this->b_Query = true;
        }
        else
        {
            Samble::getObject( "ErrorHandler" )->error('Failed to delete the following objects : <br/>');
        }
    }

    public function dbInsert($s_Table, $a_Data)
    {
        $this->clearResultSet();
        if(!is_array($a_Data)  || $s_Table == null)
        {
            Samble::getObject( "ErrorHandler" )->error('Incorrect parameters given at file: ' . __FILE__ . ' on line :' . __LINE__);
            return false;
        }
        $s_Stmt = "INSERT INTO " . $s_Table . " SET ";
        foreach($a_Data as $s_Key => $s_Value)
        {
            $s_Stmt .= " $s_Key = '$s_Value', ";
        }
        $s_Stmt = rtrim($s_Stmt, ', ');
        $this->o_Query = mysql_query($s_Stmt);
        if($this->o_Query)
        {
            $this->b_Query = true;
        }
        else
        {
            Samble::getObject( "ErrorHandler" )->error('Failed to insert the following objects : <br/>');
        }
    }

    public function dbSelect($s_Table, $a_Columns=array('*'), $s_Params="")
    {
        $this->clearResultSet();
        if($s_Table == null || !is_array($a_Columns))
        {
            Samble::getObject( "ErrorHandler" )->error('Incorrect parameters given at file: ' . __FILE__ . ' on line :' . __LINE__);
            return false;
        }
        $s_Stmt = "SELECT ";
        foreach($a_Columns as $s_Col)
        {
            $s_Stmt .= $s_Col . ", ";
        }
        $s_Stmt = rtrim($s_Stmt,', ');
        $s_Stmt .= " FROM " . $s_Table;
        $s_Stmt .= " $s_Params";
        $this->o_Query = mysql_query($s_Stmt);
        if($this->o_Query)
        {
            $this->b_Query = true;
        }
        else
        {
            Samble::getObject( "ErrorHandler" )->error('Failed to select the following objects : <br/>');
        }
    }

    public function dbUpdate($s_Table, $a_Data, $s_Params)
    {
        $this->clearResultSet();
        if($s_Table == null || !is_array($a_Data))
        {
            Samble::getObject( "ErrorHandler" )->error('Incorrect parameters given at file: ' . __FILE__ . ' on line :' . __LINE__);
            return false;
        }
        $s_Stmt = "UPDATE  $s_Table  SET ";
        foreach($a_Data as $s_Key=>$s_Value)
        {
            $s_Stmt .= " $s_Key = '$s_Value', ";
        }
        $s_Stmt = rtrim($s_Stmt,', ');
        $s_Stmt .= " $s_Params";
        $this->o_Query = mysql_query($s_Stmt);
        if($this->o_Query)
        {
            $this->b_Query = true;
        }
        else
        {
            Samble::getObject( "ErrorHandler" )->error('Failed to update the following objects : <br/>');
        }
    }
 }
?>